import { defineComponent, ref } from 'vue'
import {
  NDataTable,
  NDatePicker,
  NGrid,
  NGridItem,
  useMessage
} from 'naive-ui'
import styles from './index.module.scss'
import * as echarts from 'echarts'
import { getList, getYearList } from '@/service/modules/home';

export default defineComponent({
  name: 'home',
  setup() {
    type EChartsOption = echarts.EChartsOption

    const handleRangeChart = function () {
      const chartDomRange = document.getElementById('data-range')!
      const myChartRange = echarts.init(chartDomRange)
      let rangeOption: EChartsOption

      let temp: any[] = []

      list.value.forEach((item: any) => {
        temp.push({
          value: item.dataCount,
          name: item.tableName
        })
      })

      // eslint-disable-next-line prefer-const
      rangeOption = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          // @ts-ignore
          x: 'right',
          y: 'center'
        },
        series: [
          {
            name: '各系统流入数据占比',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 40,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: temp
          }
        ]
      }
      rangeOption && myChartRange.setOption(rangeOption)
    }

    const createColumns = [
      {
        title: '序号',
        key: 'key',
        // @ts-ignore
        render: (_, index) => {
          return `${index + 1}`
        }
      },
      { title: '系统名称', key: 'tableName' },
      { title: '总数据量(条)', key: 'dataCount' },
      { title: '今日数据量(条)', key: 'dataInputDay' },
      {
        title: '更新时间',
        key: 'updateTime',
        render(row: any) {
          if ( !row.updateTime ) {
            return ''
          } else {
            return new Date(row.updateTime).getFullYear() + '-' + ( new Date(row.updateTime).getMonth() + 1 ) + '-' + new Date(row.updateTime).getDate()
          }
        }
      }
    ]

    const above = ref({
      top1: 0,
      top2: 0,
      top3: 0,
      top4: 0,
      top5: 0
    })

    const sumData = function(list: any[], key: string): any {
      let num: number = 0;
      list.forEach((item) => {
        num = item[key] + num;
      })
      return num ? num : 0;
    }

    const handleList = function () {
      getList()
        .then((res: any) => {
          above.value.top1 = sumData(res.proportion, 'dataInputCount')
          above.value.top2 = sumData(res.proportion, 'dataOutputCount')
          above.value.top3 = sumData(res.proportion, 'dataInputDay')
          above.value.top4 = sumData(res.proportion, 'dataOutputDay')
          above.value.top5 = sumData(res.proportion, 'errorCount')
          list.value = res.list
          handleRangeChart()
        })
        .catch((err: any) => {
          message.error(err.msg ? err.msg : '接口未知错误')
        })
    }

    const year = ref(new Date())

    const handleYearList = function () {
      let date = new Date(year.value).getFullYear()
      getYearList(date.toString())
        .then((res: any) => {
          const chartDom = document.getElementById('data-year')!
          const myChart = echarts.init(chartDom)
          let yearOption: EChartsOption

          let series: any[] = []
          let legendData: any[] = []
          if ( res[0] ) {
            res[0].forEach((item: any)=>{
              legendData.push(item.tableName)
            })
          }

          legendData.forEach((item: any)=>{
            let tempData: any[] = []
            res.forEach((val: any)=>{
              val.forEach((value: any)=>{
                if ( value.tableName == item ) {
                  tempData.push(value.dataInputCount)
                }
              })
            })
            series.push({
              name: item,
              type: 'bar',
              data: tempData
            })
          })

          // eslint-disable-next-line prefer-const
          yearOption = {
            tooltip: {
              trigger: 'axis'
            },
            grid: {
              // @ts-ignore
              x: 50,
              y: 50,
              x2: 50,
              y2: 50
            },
            legend: {
              data: ['Rainfall', 'Evaporation'],
              orient: 'horizontal',
              // @ts-ignore
              x: 'center',
              y: 'bottom'
            },
            calculable: true,
            xAxis: [
              {
                type: 'category',
                // prettier-ignore
                data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
              }
            ],
            yAxis: [
              {
                type: 'value'
              }
            ],
            series: series
          }

          yearOption && myChart.setOption(yearOption)
        })
        .catch((err: any) => {
          message.error(err.msg ? err.msg : '接口未知错误')
        })
    }
    handleYearList()

    const message = useMessage()

    const list = ref([])

    handleList()

    return {
      list,
      columns: createColumns,
      handleList,
      message,
      year,
      handleYearList,
      sumData,
      above,
      handleRangeChart
    }
  },
  render() {
    return (
      <div>
        <NGrid x-gap={12} cols={5} y-gap={12}>
          <NGridItem>
            <div class={styles['top1']}>
              <div class={styles['top-num']}>{ this.above.top1 }</div>
              <div class={styles['top-desc']}>流入数据总量</div>
            </div>
          </NGridItem>
          <NGridItem>
            <div class={styles['top2']}>
              <div class={styles['top-num']}>{ this.above.top2 }</div>
              <div class={styles['top-desc']}>流出数据总量</div>
            </div>
          </NGridItem>
          <NGridItem>
            <div class={styles['top3']}>
              <div class={styles['top-num']}>{ this.above.top3 }</div>
              <div class={styles['top-desc']}>今日流入数据</div>
            </div>
          </NGridItem>
          <NGridItem>
            <div class={styles['top4']}>
              <div class={styles['top-num']}>{ this.above.top4 }</div>
              <div class={styles['top-desc']}>今日流出数据</div>
            </div>
          </NGridItem>
          <NGridItem>
            <div class={styles['top5']}>
              <div class={styles['top-num']}>{ this.above.top5 }</div>
              <div class={styles['top-desc']}>累计错误问题数</div>
            </div>
          </NGridItem>
        </NGrid>
        <div class={styles['body-chart']}>
          <div class={styles['card-header']}>
            <div class={styles['card-header-main']}>各系统流入数据</div>
            <NDatePicker
              v-model:value={this.year}
              type={'year'}
              onChange={this.handleYearList}
              clearable
            ></NDatePicker>
          </div>
          <div id={'data-year'} class={styles['data-year']}></div>
        </div>
        <div class={styles['btm']}>
          <div
            style={'width: 600px; margin-right: 10px'}
            class={styles['btm-left']}
          >
            <div class={styles['card-header']}>
              <div class={styles['card-header-main']}>各系统流入数据占比</div>
            </div>
            <div id={'data-range'} class={styles['data-range']}></div>
          </div>
          <div class={styles['btm-right']}>
            <div class={styles['card-header']}>
              <div class={styles['card-header-main']}>各系统数据情况</div>
            </div>
            <NDataTable columns={this.columns} data={this.list}></NDataTable>
          </div>
        </div>
      </div>
    )
  }
})
